//
//  NCChatInputView.m
//  AFNetworking
//
//  Created by LINAICAI on 2018/4/8.
//

#import "NCChatInputView.h"
#import "NCChatMoreInputView.h"
#import "NCChatEmoticonInputView.h"

///录音部分用别人的开源项目
#import "WBTLTalkButton.h"

static CGFloat const maxHeight = 100;
@interface NCChatInputView()<NCChatMoreInputViewDelegate,UITextViewDelegate>

@property (nonatomic , strong)UIView *nomalInputView;

@property (nonatomic , strong)UIView *zeroInputView;
///表情输入键盘
@property (nonatomic , strong)NCChatEmoticonInputView *emoticonInputView;
///更多菜单输入键盘
@property (nonatomic , strong)NCChatMoreInputView *moreInputView;
///语音输入按钮
@property (nonatomic, strong)WBTLTalkButton *talkButton;

///缓存起来的文本高度
@property (nonatomic, assign)CGFloat cacheHeight;

///语音按钮
@property (nonatomic , strong)UIButton *leftButton;
///表情按钮
@property (nonatomic , strong)UIButton *rightOtherButton;
///菜单按钮
@property (nonatomic , strong)UIButton *rightButton;
@end
@implementation NCChatInputView

#pragma mark- Setting|Getting

- (CGFloat)cacheHeight{
    if (_cacheHeight < 34) {
        return 34;
    }
    return _cacheHeight;
}
- (WBTLTalkButton *)talkButton
{
    if (_talkButton == nil) {
        _talkButton = [[WBTLTalkButton alloc] init];
        [_talkButton setHidden:YES];
        //        __weak typeof(self) weakSelf = self;
        [_talkButton setTouchBeginAction:^{
            //            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(chatBarStartRecording:)]) {
            //                [weakSelf.delegate chatBarStartRecording:weakSelf];
            //            }
        } willTouchCancelAction:^(BOOL cancel) {
            //            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(chatBarWillCancelRecording:cancel:)]) {
            //                [weakSelf.delegate chatBarWillCancelRecording:weakSelf cancel:cancel];
            //            }
        } touchEndAction:^{
            //            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(chatBarFinishedRecoding:)]) {
            //                [weakSelf.delegate chatBarFinishedRecoding:weakSelf];
            //            }
        } touchCancelAction:^{
            //            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(chatBarDidCancelRecording:)]) {
            //                [weakSelf.delegate chatBarDidCancelRecording:weakSelf];
            //            }
        }];
    }
    return _talkButton;
}
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectZero];
    }
    return _bottomView;
}
- (UIView *)topView{
    if (!_topView) {
        _topView = [[UIView alloc]initWithFrame:CGRectZero];
    }
    return _topView;
}
- (UIView *)middleView{
    if (!_middleView) {
        _middleView = [[UIView alloc]initWithFrame:CGRectZero];
    }
    return _middleView;
}
- (UIView *)zeroInputView{
    if (!_zeroInputView) {
        _zeroInputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 0)];
    }
    return _zeroInputView;
}
- (UIView *)nomalInputView{
    if (!_nomalInputView) {
        _nomalInputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 216 )];
    }
    return _nomalInputView;
}

- (NCChatEmoticonInputView *)emoticonInputView{
    if (!_emoticonInputView) {
        _emoticonInputView = [[NCChatEmoticonInputView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 216)];
        _emoticonInputView.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1.0];
    }
    return _emoticonInputView;
}
- (NCChatMoreInputView *)moreInputView{
    if (!_moreInputView) {
        ///从数据源代理拿数据来初始化键盘
        NSArray<NSString *> *titles = [self.dataSource chatInputViewMoreActionTitles];
        NSArray<UIImage *> *images = [self.dataSource chatInputViewMoreActionImages];
        
        _moreInputView = [[NCChatMoreInputView alloc]initWithTitle:titles images:images];
        _moreInputView.frame = CGRectMake(0, 0, self.bounds.size.width, 124);
        _moreInputView.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1.0];
        _moreInputView.delegate = self;
    }
    return _moreInputView;
}
- (UIButton *)rightButton{
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setImage:NCChatUIImage(@"add") forState:UIControlStateNormal];
        [_rightButton setImage:NCChatUIImage(@"add_h") forState:UIControlStateHighlighted];
        [_rightButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}
- (UIButton *)rightOtherButton{
    if (!_rightOtherButton) {
        _rightOtherButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightOtherButton setImage:NCChatUIImage(@"emoticon") forState:UIControlStateNormal];
        [_rightOtherButton setImage:NCChatUIImage(@"emoticon_h") forState:UIControlStateHighlighted];
        [_rightOtherButton setImage:NCChatUIImage(@"keyboard") forState:UIControlStateSelected];
        [_rightOtherButton addTarget:self action:@selector(emoticonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightOtherButton;
}
- (UIButton *)leftButton{
    if (!_leftButton) {
        _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftButton setImage:NCChatUIImage(@"mic") forState:UIControlStateNormal];
        [_leftButton setImage:NCChatUIImage(@"mic_h") forState:UIControlStateHighlighted];
        [_leftButton setImage:NCChatUIImage(@"keyboard") forState:UIControlStateSelected];
        [_leftButton addTarget:self action:@selector(audioAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _leftButton;
}
- (UITextView *)inputView{
    if (!_inputView) {
        _inputView = [[UITextView alloc]init];
        _inputView.delegate = self;
        _inputView.layer.borderWidth = 1;
        _inputView.layer.borderColor = [UIColor colorWithRed:216/255.0 green:216/255.0 blue:216/255.0 alpha:1.0].CGColor;
        _inputView.layer.masksToBounds = YES;
        _inputView.layer.cornerRadius = 3.0;
        _inputView.font = [UIFont systemFontOfSize:15.0];
        _inputView.returnKeyType = UIReturnKeySend;
        // _inputView.layoutManager.allowsNonContiguousLayout = NO;
        
    }
    return _inputView;
}

#pragma mark- Init
- (instancetype)initWithStatus:(NCChatInputStatus)status
{
    self = [super init];
    if (self) {
        _status = status;
        
    [self addObserver:self forKeyPath:@"status" options: NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
        
    }
    return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //拿到新值/旧值,进行操作
    NSUInteger new = change[@"new"];
    NSUInteger old = change[@"old"];
    if (new == old) {
        
    }
    else{
        [self initialize];
    }
    
    
}
- (void)dealloc
{
    NSLog(@"NCChatInputView已释放");
    ///移除KVO
    [self removeObserver:self forKeyPath:@"status"];
    ///移除表情键盘发送通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:WBEmotionDisplayBoardSendClickNotifi object:nil];
}
- (instancetype)init
{
    return [self initWithStatus:NCChatInputStatusNomal];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        ///布局
        [self setupUI];
        ///初始化一些准备工作
        [self initialize];
        ///渲染前进一步做一些准备工作
        [self prepareDisplay];
        ///通知
        [self addNoticefication];
        
        
        
    }
    return self;
}
- (void)addNoticefication{
    ///表情键盘发送通知
    __weak typeof(self) weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:WBEmotionDisplayBoardSendClickNotifi object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [weakSelf resetInputView:34];
        weakSelf.cacheHeight = 34;
    }];
}
- (void)initialize{
    switch (self.status) {

        case NCChatInputStatusText:
        {
            NSLog(@"NCChatInputStatusText");
            [self resetInputView:self.cacheHeight];
            
            [self.inputView reloadInputViews];
            [self.inputView becomeFirstResponder];
            
            [self resetHeightWithBottom:self.zeroInputView];
            
            self.talkButton.hidden = YES;
            self.inputView.hidden = NO;
            [self.leftButton setSelected:NO];
            [self.rightButton setSelected:NO];
            [self.rightOtherButton setSelected:NO];
            ///文本输入键盘本身能触发通知,这里不需要再发送通知了
            
        }
            break;
            
        case NCChatInputStatusNomal:
        {
            NSLog(@"NCChatInputStatusNomal");
            [self resetInputView:self.cacheHeight];
            
            [self.inputView resignFirstResponder];
            [self resetHeightWithBottom:self.zeroInputView];
            
            self.talkButton.hidden = YES;
            self.inputView.hidden = NO;
            [self.rightOtherButton setSelected:NO];
            [self.rightButton setSelected:NO];
            [self.leftButton setSelected:!self.leftButton.isSelected];
            
            [self sendWillHidNotification];
        }
            break;
        case NCChatInputStatusAudio:
        {
            NSLog(@"NCChatInputStatusAudio");
            ///语音键盘弹出前保存下文本高度,方便恢复
            [self resetInputView:34];
            
            self.inputView.inputView = nil;
            [self.inputView reloadInputViews];
            [self.inputView resignFirstResponder];
            
            [self resetHeightWithBottom:self.zeroInputView];
            
            self.talkButton.hidden = NO;
            self.inputView.hidden = YES;
            [self.rightOtherButton setSelected:NO];
            [self.rightButton setSelected:NO];
            [self.leftButton setSelected:!self.leftButton.isSelected];
            
            [self sendWillHidNotification];
        }
            break;
        case NCChatInputStatusEmoticon:
        {
            NSLog(@"NCChatInputStatusEmoticon");
            [self resetInputView:self.cacheHeight];
            
            self.inputView.inputView = nil;
            [self.inputView reloadInputViews];
            [self.inputView resignFirstResponder];
            
            
            [self resetHeightWithBottom:self.emoticonInputView];
            
            self.talkButton.hidden = YES;
            self.inputView.hidden = NO;
            [self.rightButton setSelected:NO];
            [self.leftButton setSelected:NO];
            [self.rightOtherButton setSelected:!self.rightOtherButton.isSelected];
            [self sendWillHidNotification];
        }
            break;
        case NCChatInputStatusMore:
        {
            NSLog(@"NCChatInputStatusMore");
            [self resetInputView:self.cacheHeight];
            
            self.inputView.inputView = nil;
            [self.inputView reloadInputViews];
            [self.inputView resignFirstResponder];

            [self resetHeightWithBottom:self.moreInputView];
            
            self.talkButton.hidden = YES;
            self.inputView.hidden = NO;
            [self.rightOtherButton setSelected:NO];
            [self.leftButton setSelected:NO];
            [self.rightButton setSelected:!self.rightButton.isSelected];
            [self sendWillHidNotification];
        }
            break;
            
        default:
            break;
    }
}
- (void)sendWillHidNotification{
    ///告诉监听器,弹出的键盘高度
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithCGRect:self.bottomView.bounds],UIKeyboardFrameEndUserInfoKey, nil];
    
    ///发送通知要隐藏键盘
    [[NSNotificationCenter defaultCenter]postNotificationName:UIKeyboardWillHideNotification object:nil userInfo:userInfo];
}
- (void)sendWillShowNotification{
    ///告诉监听器,弹出的键盘高度
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithCGRect:self.bottomView.bounds],UIKeyboardFrameEndUserInfoKey, nil];
    
    ///发送通知要隐藏键盘
    [[NSNotificationCenter defaultCenter]postNotificationName:UIKeyboardWillShowNotification object:nil userInfo:userInfo];
    
}
- (void)resetHeightWithTop:(UIView *)top{
    
    [self.topView removeFromSuperview];
    self.topView = top;
    
    [self addSubview:self.topView];
    NSLog(@"self.topView:%@",NSStringFromCGRect(self.topView.bounds));
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.mas_equalTo(self.topView.bounds.size.height);
        make.bottom.equalTo(self.middleView.mas_top);
    }];
    [self layoutIfNeeded];
}
- (void)resetHeightWithBottom:(UIView *)bottom{

    [self.bottomView removeFromSuperview];
    self.bottomView = bottom;
    
    [self addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(self.bottomView.bounds.size.height);
        make.top.equalTo(self.middleView.mas_bottom);
    }];
    [self layoutIfNeeded];
}
- (void)setupUI{
    [self addSubview:self.bottomView];
    [self addSubview:self.topView];
    [self addSubview:self.middleView];
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.mas_equalTo(0);
        make.bottom.equalTo(self.middleView.mas_top);
    }];
    [self.middleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
    }];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(0);
        make.top.equalTo(self.middleView.mas_bottom);
    }];
    
    [self.middleView addSubview:self.leftButton];
    [self.middleView addSubview:self.rightButton];
    [self.middleView addSubview:self.rightOtherButton];
    [self.middleView addSubview:self.inputView];
    [self.middleView addSubview:self.talkButton];
    
    [self.leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.bottom.equalTo(self.inputView.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(33, 33));
        
    }];
    
    
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-15);
        make.bottom.equalTo(self.inputView.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(33, 33));
        
    }];
    

    [self.rightOtherButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.rightButton.mas_left).offset(-15);
        make.bottom.equalTo(self.inputView.mas_bottom);
        make.size.mas_equalTo(CGSizeMake(33, 33));
        
    }];
    
    
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.leftButton.mas_right).offset(10);
        make.right.equalTo(self.rightOtherButton.mas_left).offset(-10);
        make.bottom.equalTo(self.middleView.mas_bottom).offset(-10);
        make.top.equalTo(self.middleView.mas_top).offset(10);
        make.height.mas_equalTo(34);
    }];
    
    
    [self.talkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.leftButton.mas_right).offset(10);
        make.right.equalTo(self.rightOtherButton.mas_left).offset(-10);
        make.bottom.equalTo(self.middleView.mas_bottom).offset(-10);
        make.height.mas_equalTo(34);
        
    }];
    
    

}
- (void)prepareDisplay{
    self.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1.0];
}
#pragma mark- Action


- (void)emoticonAction:(UIButton *)sender{
    if (sender.isSelected) {
        //弹起文本
        self.status = NCChatInputStatusText;
    }
    else{
        //弹起表情
        self.status = NCChatInputStatusEmoticon;
    }

}
- (void)audioAction:(UIButton *)sender{
    if (sender.isSelected) {
        //弹起文本
        self.status = NCChatInputStatusText;
    }
    else{
        //弹起录音
        self.status = NCChatInputStatusAudio;
    }
    
    
    
}
- (void)moreAction:(UIButton *)sender{
    if (sender.isSelected) {
        //弹起文本
        self.status = NCChatInputStatusText;
    }
    else{
        //弹起菜单
        self.status = NCChatInputStatusMore;
    }
    
}
- (void)resetInputView:(CGFloat)height{
    ///设置高度
    [UIView animateWithDuration:0.25 animations:^{
        [self.inputView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(height);
        }];
        [self.middleView layoutIfNeeded];
    }];

    
}
#pragma mark- NCChatMoreInputViewDelegate
- (void)NCChatMoreInputViewDidClickAt:(NSIndexPath *)indexPath{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatInputViewMoreActionWithIndexPath:)]) {
        [self.delegate chatInputViewMoreActionWithIndexPath:indexPath];
        
    }
}
#pragma mark- UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView{
    self.status = NCChatInputStatusText;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatInputViewSendText:)]) {
            [self.delegate chatInputViewSendText:textView.text];
            ///重置输入框
            [self resetInputView:34];
            self.cacheHeight = 34;
        }
        //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        return NO;
        //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
    NSLog(@"Height:%f",textView.contentSize.height);
    if (textView.contentSize.height > maxHeight) {
        ///如果高度超过了最大高度,就让输入框滚到底部
        [textView scrollRectToVisible:CGRectMake(0, textView.contentSize.height-15, textView.contentSize.width, 20) animated:YES];

    }
    else if(textView.contentSize.height != textView.bounds.size.height){
        [self resetInputView:textView.contentSize.height];
        self.cacheHeight = textView.contentSize.height;

    }

}
@end
